package db

import (
	"errors"
	"fmt"
	"github.com/redis/go-redis/v9"
	"golang.org/x/net/context"
	"lib/config"
)

var redisClient *redis.Client

// Redis 在中间件中初始化redis链接
func InitRedis(rcf *config.Redis) error {
	//conf := global.GvaConfig.Redis
	if rcf == nil || rcf.Address == "" {
		return errors.New("未设置 Redis 地址")
	}
	// 链接redis
	client := redis.NewClient(&redis.Options{
		Network:  rcf.Network,
		Addr:     fmt.Sprintf("%s:%s", rcf.Address, rcf.Port),
		Password: rcf.Password,
		DB:       rcf.Database,
		PoolSize: rcf.PoolSize,
	})
	_, err := client.Ping(context.Background()).Result()
	if err != nil {
		return err
	}
	redisClient = client
	return nil
}

func GetRedisClient() *redis.Client {
	return redisClient
}
